#include "config.h"
#include <iostream>
#include <fstream>
#include <map>

using namespace std;

//void Config::output(){
//	map<string,string>::iterator it;
//	for(it = content.begin();it != content.end();++it)
//		cout<<"key:"<<(*it).first<<"\t"
//			<<"value:"<<(*it).second<<"\n";
//	cout<<"\n\n";
//}

bool Config::Load(const string& path){
	ifstream infile;
	string mid;
	string first="";
	string second="";
	bool isFirst = true;

	configPath = path;
	infile.open(path.c_str());
	if(!infile){
		cout<<"Error:unable to open the file.";
		return false;
	}
	while(infile>>mid){
		if(isFirst){
			if(mid == "\n"){
				isFirst = true;
			}
			else if (mid == ":="){
				isFirst = false;
			}
			else {
				first = mid;
			}
		}
		else{
			if(mid == "\n"){
				isFirst = true;
			}
			else if(mid == ":="){
				isFirst = false;
			}
			else{
				second = mid;
				content[string(first)] = second;
				isFirst = true;
			}
		}
	}
	return true;
}

bool Config::Save(){
	return Save(configPath);
}

bool Config::Save(const string& path){
	ofstream outfile;
	outfile.open(configPath.c_str());
	if(!outfile){
		cout<<"Error:unable to open the file.";
		return false;
	}
	map<string,string>::iterator it;
	for(it = content.begin();it != content.end();++it){
		outfile << (*it).first << " := " << (*it).second << "\n";
	}
	return true;
}

bool Config::Set(const string& key, const string& value){
	if(content.count(key)){
		content[key] = value;
	}
	else{
		content[string(key)] = value;
	}
	return true;
}

string Config::Get(const string& key){
	if(content.count(key))
		return content[key];
	return "";
}

string Config::configPath;
map<string,string> Config::content;